package com.ckzp.weixin;

import com.alibaba.fastjson.JSON;
import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonResult;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.core.util.HtmlUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.weixin.model.WxUserToken;
import com.jfinal.kit.HttpKit;

import javax.swing.text.html.HTML;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 51594 on 2022/8/15.
 */
public class AppTool {


    /**
     * 根据 CODE取得用户的OPENID
     * <p/>
     * https://api.weixin.qq.com/sns/jscode2session?appid=&secret=&js_code=&grant_type=authorization_code
     *
     * @param code
     * @return
     */
    public static WxUserToken getWxAppToken(String code) {
        String url = "";
        try {
            code = HtmlUtil.decode(code);
            String appid = WxTool.getAppID();
            String appsecret = WxTool.getAppSecret();
            url = "https://api.weixin.qq.com/sns/jscode2session?" +
                    "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "" +
                    "&grant_type=authorization_code";
            String result = HttpKit.get(url);
            Object o = JSON.parseObject(result, WxUserToken.class);
            if (o instanceof WxUserToken) {
                return (WxUserToken) o;
            } else {
                return new WxUserToken().setErrcode("9").setErrmsg("未知");
            }
        } catch (Exception e) {
            System.out.println("getWxAppToken url==" + url);
            e.printStackTrace();
            return new WxUserToken().setErrcode("9").setErrmsg(e.getMessage());
        }
    }

    /**
     * 取得手机号
     *
     * @param code
     * @return
     */
    public static JsonResult getPhoneNumber(String code) {
        String phonenumber = "";
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + AccessTokenTool.getAccessToken();
        Jmode data = Jmode.n().set("code", code);
        Map<String, String> headers = new HashMap<String, String>(16);
        headers.put("Content-Type", "application/json");
        String result = HttpKit.post(url, null, data.toJson(), headers);
        Map o = JSON.parseObject(result, Map.class);
        if ("0".equals(StringUtil.getString(o, "errcode"))) {
            Map phone_info = (Map) o.get("phone_info");
            if (phone_info != null) {
                phonenumber = StringUtil.getString(phone_info, "phoneNumber");
            }
            return JsonResult.getResult().setData(phonenumber);
        } else {
            return JsonResult.getResult().setCode(9).setData(result);
        }
    }

    public static void main(String[] arg) {

    }
}
